package day21.zhiyou100;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

// 接收端
class ReceiveUDP3 {
    public static void main(String[] args) throws Exception {
        // DatagramPacket
        DatagramSocket ds = new DatagramSocket(8088);
        // DatagramSocket
        // 接收数据报信息
        System.out.println("开始接收发送端发送的信息：");
        while (true) {
            byte[] data = new byte[1024*64];
            DatagramPacket dp = new DatagramPacket(data, data.length);
            ds.receive(dp);
            // 查看接收到的信息
            byte[] content = dp.getData();
            String receiveContent = new String(content, 0, dp.getLength());
            // 转换成字符串打印输出
            System.out.println("发送的内容："+receiveContent);// dp.getLength() 从数据报中获取的字节个数
            int port = dp.getPort();
            System.out.println("发送端的端口号：" + port);
            InetAddress address = dp.getAddress();
            System.out.println("发送端的地址："+ address);
            // 结束接收信息
            if (receiveContent.contains("end")){
                break;
            }
        }
        ds.close();
    }
}


public class SendUDP3 {

    public static void main(String[] args) throws Exception{
        // DatagramPacket  使用四个参数：  字节数组  字节个数  ip地址  端口号
        /*
            public DatagramPacket(byte buf[], int length,
                          InetAddress address, int port) {
                     this(buf, 0, length, address, port);
            }
         */
        // DatagramSocket
        DatagramSocket ds = new DatagramSocket();// 0-65535
        String content = "";
        // InetAddress
        InetAddress address = InetAddress.getLocalHost();
        Scanner scanner = new Scanner(System.in);
        System.out.println("开始往接收端发送信息：");
        while (true) {
            String sendContent = scanner.next();
            byte[] bytes = sendContent.getBytes();
            DatagramPacket dp = new DatagramPacket(bytes, bytes.length, address, 8088);
            ds.send(dp);
            if (sendContent.contains("end")){
                break;
            }
        }
        // 构建发送的数据报信息
        // 发送数据报信息
        ds.close();
    }


}
